package operation;

import book.Book;
import book.BookList;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA
 * Description:  删除图书
 */
public class DelOperation implements IOperation{
    @Override
    public void work(BookList bookList){
        System.out.println("删除图书...");

        System.out.println("请输入要删除的图书:");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();

        int currentSize = bookList.getUsedSize();//当前书架上书本的数目
        int index = -1;//记录要删除的图书的位置
        for (int i = 0; i < currentSize; i++) {
            Book book = bookList.getBook(i);
            if(book.getName().equals(name)) {
                index = i;
                break;
            }
        }

        if(index == -1) {
            System.out.println("在书架上找不到您想要删除的书。");
            return ;
        }else {
            for (int i = index + 1; i < currentSize; i++) {
                Book book = bookList.getBook(i);
                bookList.setBook(i-1,book);
                if(i == currentSize - 1) {
                    //原来最后一本书的位置要变成 null
                    bookList.setBook(i,null);

                    //别忘了此时书本的数目要 -1
                    bookList.setUsedSize(currentSize-1);
                }
            }

            System.out.println("该图书删除完毕!");
        }
    }
}
